package utils

import (
	"golang.org/x/image/font"
	"golang.org/x/image/font/opentype"
	"golang.org/x/image/math/fixed"
	"image"
	"image/draw"
	"image/jpeg"
	"io"
	"os"
)

func loadFont() (font.Face, error) {
	fontData, err := os.ReadFile("static/arial.ttf") // 假设字体文件是arial.ttf
	if err != nil {
		return nil, err
	}
	ttf, err := opentype.Parse(fontData)
	if err != nil {
		return nil, err
	}
	const fontSize = 24.0
	face, err := opentype.NewFace(ttf, &opentype.FaceOptions{
		Size:    fontSize,
		DPI:     72,
		Hinting: font.HintingFull,
	})
	return face, err
}

func Draw(file string, text string, w io.Writer) {
	// 打开原始图片
	originalFile, err := os.Open(file)
	if err != nil {
		panic(err)
	}
	defer originalFile.Close()

	original, err := jpeg.Decode(originalFile)
	if err != nil {
		panic(err)
	}
	bounds := original.Bounds()
	face, err := loadFont()
	if err != nil {
		panic(err)
	}
	size, _ := font.BoundString(face, text)
	if fixed.Int26_6(bounds.Dx()*64) < (size.Max.X-size.Min.X)*2 ||
		fixed.Int26_6(bounds.Dy()*64) < (size.Max.Y-size.Min.Y)*2 {
		if bs, err := io.ReadAll(originalFile); err == nil {
			w.Write(bs)
		}
		return
	}

	target := image.NewRGBA(bounds)
	draw.Draw(target, bounds, original, image.Point{0, 0}, draw.Src)
	(&font.Drawer{
		Dst:  target,
		Src:  image.Black,
		Face: face,
		Dot: fixed.Point26_6{
			X: fixed.Int26_6(bounds.Dx() / 2 * 64),
			Y: fixed.Int26_6(bounds.Dy() / 2 * 64),
		},
	}).DrawString(text)
	(&font.Drawer{
		Dst:  target,
		Src:  image.White,
		Face: face,
		Dot: fixed.Point26_6{
			X: fixed.Int26_6(bounds.Dx() / 2 * 64),
			Y: fixed.Int26_6((bounds.Dy()/2+20)*64) + size.Max.Y - size.Min.Y,
		},
	}).DrawString(text)

	err = jpeg.Encode(w, target, &jpeg.Options{Quality: 100})
	if err != nil {
		panic(err)
	}
}
